function MWCStruct = Set_MWC(Signal,SignPatterns, q,SBR,fp,M, HardwareChannels)
% This function set all the parameters of the MWC automatially, based on a
% given model parameters N,B,fmax. For correct results, it is recomanded to
% leave as many parameters as possible to default, unless you understand
% excatly the changes you are making

%assign optional veriables
if( isempty(q) )
    q=1;
end

MWCStruct = struct ;

% read signal parameters
N       = Signal.N;
B       = Signal.B;
fmax    = Signal.fmax;
fnyq = 2*fmax;

 if(strmatch(SBR, 'SBR2'))
         MWCStruct = setfield(MWCStruct, 'SBR', 'SBR2');
         m = ceil(2*N/q);
  elseif (strmatch(SBR, 'SBRspecial'))
          MWCStruct = setfield(MWCStruct, 'SBR', 'SBRspecial');
         m = ceil(2*N/q);
 else
         MWCStruct = setfield(MWCStruct, 'SBR', 'SBR4');
%          m = ceil(4*N/q);
        m=HardwareChannels; % FIXME: Shahar - only this works
 end
 
 
%Reflect the HW constraint of channels
if (~isempty(HardwareChannels))
    m = max(HardwareChannels,m);
end

%Automitically set fp if needed
if (isempty(fp))
    fp = B * 1.1; 
end
Tp=1/fp;

%Compute sampling rate
fs =q* fp;

%Automitically set L(aliasing rate)  if needed
if ( ~isempty(M))
    L = M - q + 1;
else    
    L = ceil(fnyq/fp);
        if mod(L,2)==0
            L=L+1;
        end
end

%Automitically set length of sequence if needed
if (isempty(M) )
    if (isempty(SignPatterns) )
        M = L + q - 1;
    else
        M  = size(SignPatterns,2);
    end
end

%Compute random sequence if none was specidfied
if( isempty(SignPatterns))
    SignPatterns =  RandSource(m,M);
end

%% write MWC values to struct
MWCStruct = setfield(MWCStruct, 'L', L); 
MWCStruct = setfield(MWCStruct, 'm', m); 
MWCStruct = setfield(MWCStruct, 'fcut', fs/2);   % filter cutoff
MWCStruct = setfield(MWCStruct, 'fs', fs);   % sampling rate per channel
MWCStruct = setfield(MWCStruct, 'Ts', 1/fs);   % sampling rate per channel
MWCStruct = setfield(MWCStruct, 'q', q);   % Expanding factor
MWCStruct = setfield(MWCStruct, 'Speed', 1/(Tp/M));
MWCStruct = setfield(MWCStruct, 'fp', fp);
MWCStruct = setfield(MWCStruct, 'M', M);  % number of alternations
MWCStruct = setfield(MWCStruct, 'SignPatterns',SignPatterns );   
end
